package cn.ichiva.web.common;

import com.bosi.message.Message;
import com.bosi.message.MessageService;
import com.bosi.message.impl.SimpleMessageService;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
 * 消息中心
 */
public class Bus {
    final static MessageService service = new SimpleMessageService();

    /**
     * 订阅
     * @param topic
     * @param consumer
     */
    public static String subscribe(Topic topic, Consumer<String> consumer){
        HashMap<String, Object> header = new HashMap<>();
        header.put("topic",topic.name());
        return service.subscribe(header, e -> consumer.accept(e.getContext()));
    }

    /**
     * 退订
     * @param id
     */
    public static void unsubscribe(String id){
        service.unsubscribe(id);
    }

    public static void publish(Topic topic,String content){
        Message message = new Message();
        HashMap<String, Object> header = new HashMap<>();
        header.put("topic",topic.name());
        message.setHeader(header);
        message.setType(0);
        message.setContext(content);
        service.publish(message);
    }
}
